"""
散客比赛相关 API
"""
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import List, Optional
from datetime import datetime, timedelta
from app.core.database import get_db
from app.core.dependencies import get_current_user
from app.schemas.match import (
    MatchResponse, MatchCreate, MatchUpdate
)
from app.schemas.common import ApiResponse, PageData
from app.models.match import Match, MatchPlayer
from app.models.user import User
from app.utils.helpers import generate_id

router = APIRouter()


@router.get("/list", response_model=ApiResponse[PageData[MatchResponse]])
async def get_match_list(
    cityId: Optional[str] = Query(None),
    date: Optional[str] = Query(None),
    page: int = Query(1, ge=1),
    pageSize: int = Query(10, ge=1, le=100),
    db: Session = Depends(get_db)
):
    """获取散客比赛列表"""
    query = db.query(Match)
    
    if cityId:
        # TODO: 通过 venue_id 关联查询 city_id
        pass
    
    if date:
        query = query.filter(Match.date == date)
    else:
        # 默认只显示未来的比赛
        today = datetime.now().strftime("%Y-%m-%d")
        query = query.filter(Match.date >= today)
    
    query = query.order_by(Match.date.asc(), Match.start_time.asc())
    
    total = query.count()
    matches = query.offset((page - 1) * pageSize).limit(pageSize).all()
    
    # 构造响应（包含球员列表）
    match_list = []
    for match in matches:
        players = db.query(MatchPlayer).filter(MatchPlayer.match_id == match.id).all()
        match_dict = match.to_dict()
        match_dict["players"] = [p.to_dict() for p in players]
        match_list.append(MatchResponse(**match_dict))
    
    return ApiResponse(
        data=PageData(
            list=match_list,
            total=total,
            page=page,
            pageSize=pageSize,
            hasMore=total > page * pageSize
        )
    )


@router.get("/individual-list", response_model=ApiResponse[List[MatchResponse]])
async def get_individual_match_list(
    cityId: Optional[str] = Query(None),
    date: Optional[str] = Query(None),
    db: Session = Depends(get_db)
):
    """获取散客比赛列表（简化版，用于下拉选择）"""
    query = db.query(Match)
    
    if date:
        query = query.filter(Match.date == date)
    
    matches = query.order_by(Match.date.asc()).limit(50).all()
    
    match_list = []
    for match in matches:
        match_dict = match.to_dict()
        match_list.append(MatchResponse(**match_dict))
    
    return ApiResponse(data=match_list)


@router.get("/individual-detail/{match_id}", response_model=ApiResponse[MatchResponse])
async def get_match_detail(
    match_id: str,
    db: Session = Depends(get_db)
):
    """获取散客比赛详情"""
    match = db.query(Match).filter(Match.id == match_id).first()
    if not match:
        raise HTTPException(status_code=404, detail="比赛不存在")
    
    # 查询球员列表
    players = db.query(MatchPlayer).filter(MatchPlayer.match_id == match_id).all()
    
    match_dict = match.to_dict()
    match_dict["players"] = [p.to_dict() for p in players]
    
    return ApiResponse(data=MatchResponse(**match_dict))


@router.post("/create", response_model=ApiResponse[MatchResponse])
async def create_match(
    match_data: MatchCreate,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """创建散客比赛（发布招募）"""
    # 创建比赛
    deadline = datetime.strptime(
        f"{match_data.date} {match_data.startTime}",
        "%Y-%m-%d %H:%M"
    ) - timedelta(hours=2)  # 提前2小时截止报名
    
    match = Match(
        id=generate_id(),
        venue_id=match_data.venueId,
        venue_name=match_data.venueName,
        latitude=match_data.latitude,
        longitude=match_data.longitude,
        address=match_data.address,
        date=match_data.date,
        start_time=match_data.startTime,
        end_time=match_data.endTime,
        deadline=deadline,
        type=match_data.type,
        price_per_person=match_data.pricePerPerson,
        current_players=1,  # 发布者自己
        max_players=match_data.maxPlayers,
        min_players=match_data.minPlayers,
        publisher_id=current_user.id,
        publisher_name=current_user.nick_name,
        positions=match_data.positions or {},
        note=match_data.note
    )
    
    db.add(match)
    
    # 添加发布者为第一个球员
    player = MatchPlayer(
        id=generate_id(),
        match_id=match.id,
        user_id=current_user.id,
        user_name=current_user.nick_name,
        avatar=current_user.avatar,
        position="",
        rating=current_user.rating
    )
    db.add(player)
    
    db.commit()
    db.refresh(match)
    
    match_dict = match.to_dict()
    match_dict["players"] = [player.to_dict()]
    
    return ApiResponse(data=MatchResponse(**match_dict))


@router.post("/join", response_model=ApiResponse[str])
async def join_match(
    matchId: str,
    position: Optional[str] = None,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """加入散客比赛"""
    match = db.query(Match).filter(Match.id == matchId).first()
    if not match:
        raise HTTPException(status_code=404, detail="比赛不存在")
    
    # 检查是否已加入
    existing = db.query(MatchPlayer).filter(
        MatchPlayer.match_id == matchId,
        MatchPlayer.user_id == current_user.id
    ).first()
    if existing:
        raise HTTPException(status_code=400, detail="已加入该比赛")
    
    # 检查人数限制
    if match.current_players >= match.max_players:
        raise HTTPException(status_code=400, detail="比赛人数已满")
    
    # 检查报名截止时间
    if match.deadline and datetime.now() > match.deadline:
        raise HTTPException(status_code=400, detail="报名已截止")
    
    # 添加球员
    player = MatchPlayer(
        id=generate_id(),
        match_id=matchId,
        user_id=current_user.id,
        user_name=current_user.nick_name,
        avatar=current_user.avatar,
        position=position or "",
        rating=current_user.rating
    )
    db.add(player)
    
    # 更新比赛人数
    match.current_players += 1
    
    # 如果指定了位置，更新位置需求
    if position and match.positions and position in match.positions:
        match.positions[position]["current"] += 1
    
    db.commit()
    
    return ApiResponse(data="报名成功")


@router.post("/quit", response_model=ApiResponse[str])
async def quit_match(
    matchId: str,
    current_user: User = Depends(get_current_user),
    db: Session = Depends(get_db)
):
    """退出散客比赛"""
    match = db.query(Match).filter(Match.id == matchId).first()
    if not match:
        raise HTTPException(status_code=404, detail="比赛不存在")
    
    # 发布者不能退出自己发布的比赛
    if match.publisher_id == current_user.id:
        raise HTTPException(status_code=400, detail="发布者不能退出，如需取消请删除比赛")
    
    # 查找球员记录
    player = db.query(MatchPlayer).filter(
        MatchPlayer.match_id == matchId,
        MatchPlayer.user_id == current_user.id
    ).first()
    
    if not player:
        raise HTTPException(status_code=400, detail="未加入该比赛")
    
    # 删除球员记录
    db.delete(player)
    
    # 更新比赛人数
    match.current_players -= 1
    
    # 更新位置需求
    if player.position and match.positions and player.position in match.positions:
        match.positions[player.position]["current"] -= 1
    
    db.commit()
    
    return ApiResponse(data="已退出比赛")

